const express = require('express')
const Router = express.Router()
const query = require('./db')

module.exports = Router

//获取商品列表
Router.get('/getGoodsList', async (req, res) => {
    try {
        let data = await query(`select * from goods`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '没有商品信息'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取商品列表成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

//获取商品详情
Router.get('/getGoodsDetail', async (req, res) => {
    try {
        let { goods_id } = req.query
        // let data = await query(`select * from goods join sku on goods.goods_id=sku.sku_goods_id where goods_id=${goods_id}`)
        let goods = await query(`select * from goods where goods_id=${goods_id}`)
        let goods_group = goods[0].goods_group
        let goodsGroup = await query(`select * from goods where goods_group='${goods_group}'`)

        // let goods_group = goods[0].goods_group
        if (goods.length === 0) {
            res.send({
                code: 400,
                msg: '获取商品详情失败'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取商品详情成功',
            data: {
                goods,
                goodsGroup
            }
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

// 获取同品类商品
Router.get('/getGroupGoods', async (req, res) => {
    try {
        let { goods_group } = req.query
        let data = await query(`select * from goods where goods_group='${goods_group}'`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: 'no'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取同品类商品成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

// 获取商品规格
Router.get('/getSku', async (req, res) => {
    try {
        let { goods_id } = req.query
        let data = await query(`select * from sku where sku_goods_id=${goods_id}`)
        if (data.length === 0) {
            res.send({
                code: 400,
                msg: '获取商品规格失败'
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取商品规格成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})